<template>
  <div ref="riskGraph" class="graph-container"></div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  name: 'RiskChart',
  props: {
    startNode: {
      type: String,
      required: true
    },
    failedNodes: {
      type: Array,
      required: true
    }
  },
  watch: {
    // 监听数据变化，重新渲染图
    startNode() {
      this.initChart();
    },
    failedNodes() {
      this.initChart();
    }
  },
  mounted() {
    this.initChart();
    window.addEventListener('resize', this.resizeChart); // 监听窗口大小变化
  },
  methods: {
    initChart() {
      console.log('RiskChart init');
      console.log('startNode:', this.startNode);
      console.log('failedNodes:', this.failedNodes);

      // 初始化图表
      this.riskChart = echarts.init(this.$refs.riskGraph);

      // 构建数据节点
      const nodeSet = new Set([this.startNode, ...this.failedNodes]);
      const data = Array.from(nodeSet).map(name => {
        return {
          name,
          itemStyle: {
            color: name === this.startNode ? '#e20a0a' : '#2061dc'  // 起始节点红色，其他蓝色
          }
        };
      });

      // 构建连接
      const links = this.failedNodes.map(target => {
        return {
          source: this.startNode,
          target: target,
          lineStyle: {
            color: '#cb3b3b',
            width: 2
          }
        };
      });

      const riskOption = {
        tooltip: {
          formatter: '{b}'
        },
        animationDurationUpdate: 1500,
        animationEasingUpdate: 'quinticInOut',
        series: [
          {
            type: 'graph',
            layout: 'force',
            symbolSize: 50,
            roam: true,
            draggable: true,
            label: {
              show: true,
              position: 'right',
              formatter: '{b}',
              fontSize: 12
            },
            edgeSymbol: ['circle', 'arrow'],
            edgeSymbolSize: [4, 10],
            edgeLabel: {
              fontSize: 12
            },
            data: data,
            links: links,
            lineStyle: {
              opacity: 0.9,
              width: 2,
              curveness: 0
            },
            force: {
              repulsion: 200,
              edgeLength: 150
            }
          }
        ]
      };

      this.riskChart.setOption(riskOption);
    },
    resizeChart() {
      if (this.riskChart) {
        this.riskChart.resize();
      }
    }
  },
  beforeDestroy() {
    if (this.riskChart) {
      this.riskChart.dispose();
    }
    window.removeEventListener('resize', this.resizeChart);
  }
};
</script>

<style scoped>
.graph-container {
  /* 调整宽度和高度 */
  width: 1120px;
  height: 700px;
  display: flex;
  justify-content: center;
  align-items: center;
//border: 1px solid #2c2a2a;
//border-radius: 4px;
  position: relative;
}
</style>
